
import cv2

img = cv2.imread("chepai2.jpg")
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow("gray", img_gray)
cv2.waitKey(0)

img_thre = img_gray
cv2.threshold(img_gray, 100, 255, cv2.THRESH_BINARY_INV, img_thre)
cv2.imshow("threshold", img_thre)
cv2.waitKey(0)

cv2.imwrite("thre_res.png", img_thre)

white = []
black = []
height = img_thre.shape[0]
width = img_thre.shape[1]
white_max = 0
black_max = 0

for i in range(width):
    s = 0
    t = 0
    for j in range(height):
        if img_thre[j][i] == 255:
            s += 1
        if img_thre[j][i] == 0:
            t += 1
    white_max = max(white_max, s)
    black_max = max(black_max, t)
    white.append(s)
    black.append(t)
    print(s)
    print(t)

arg = False
if black_max > white_max:
    arg = True


def find_end(start_):
    end_ = start_ + 1
    for m in range(start_ + 1, width - 1):
        if (black[m] if arg else white[m]) > (0.95 * black_max if arg
        else 0.95 * white_max):
            end_ = m
            break
    return end_


n = 1
start = 1
end = 2
while n < width - 2:
    n += 1
    if (white[n] if arg else black[n]) > (0.05 * white_max if arg
    else 0.05 * black_max):
        start = n
        end = find_end(start)
        n = end
        if end - start > 5:
            cj = img_thre[1:height, start:end]
            cv2.imshow("caijian", cj)
            cv2.waitKey(0)